<template>
  <div class="login">
    <img
      class="logo"
      src="@/assets/imgs/login-logo.png"
      alt=""
    />
    <div class="login-box">
      <section class="login-panel">
        <div class="login-card">
          <div class="title">欢迎<span>登录</span> </div>
          <el-input
            v-if="loginForm.loginType === 1"
            class="form-item"
            v-model="loginForm.username"
            :maxlength="20"
            placeholder="请输入账号"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <img src="@/assets/imgs/user-icon.png" />
            </template>
          </el-input>
          <el-input
            class="form-item"
            v-if="loginForm.loginType === 1"
            v-model="loginForm.password"
            :maxlength="16"
            type="password"
            :show-password="true"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <img src="@/assets/imgs/password-icon.png" />
            </template>
          </el-input>
          <el-input
            v-if="loginForm.loginType === 2"
            class="form-item"
            v-model="loginForm.mobile"
            :maxlength="11"
            @blur="validPhone"
            placeholder="请输入手机号"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <img src="@/assets/imgs/user-icon.png" />
            </template>
            <template #suffix>
              <img
                v-if="isShowIcon"
                :src="isRegisterIcon"
              />
            </template>
          </el-input>
          <slide-verify
            v-if="loginForm.loginType === 2"
            ref="slideVerifyRef"
            class="form-item cursor-pointer"
            @success="onVerifySuccess"
          />
          <el-input
            class="form-item"
            v-if="loginForm.loginType === 2"
            v-model="loginForm.code"
            :maxlength="6"
            placeholder="请输入验证码"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <img src="@/assets/imgs/verify-icon.png" />
            </template>
            <template #suffix>
              <el-button
                v-show="validMess === '获取验证码'"
                :disabled="
                  isVerifySuccess || (isRegister && !userId)
                "
                type="primary"
                link
                @click="getVerifyCode"
                >{{ validMess }}</el-button
              >
              <el-button
                v-show="validMess !== '获取验证码'"
                class="count-btn"
                type="primary"
                link
                >{{ validMess }}</el-button
              >
            </template>
          </el-input>
          <div class="flex justify-between">
            <el-button link @click="openRegisterForm"
              >申请注册</el-button
            >
            <el-button
              link
              v-if="loginForm.loginType === 1"
              @click="openForgotForm"
              >忘记密码</el-button
            >
          </div>
          <el-button
            size="large"
            class="w-full"
            type="primary"
            @click="handleLogin"
            >登录</el-button
          >
          <div class="other-way">
            <span class="label">其他登录方式</span>
            <img
              class="cursor-pointer"
              @click="toggleWay"
              :src="switchImg"
              @mouseover="switchMouseover"
              @mouseleave="switchMouseleave"
            />
            <span
              class="cursor-pointer text-center"
              @click="toggleWay"
              >{{ loginWayText }}</span
            >
          </div>
          <img
            v-if="false"
            src="@/assets/imgs/login-qr.png"
          />
        </div>
      </section>
    </div>
    <a href="https://beian.miit.gov.cn" target="_blank">
      陕ICP备2023014915号-10
    </a>
  </div>
  <AuthorizeForm
    ref="authorizeFormRef"
    @success="authorizeCallback"
  ></AuthorizeForm>
  <EnterpriseForm
    ref="enterpriseFormRef"
    @success="enterpriseCallback"
  ></EnterpriseForm>
  <RegisterForm ref="registerFormRef"></RegisterForm>
  <ForgotForm ref="forgotFormRef"></ForgotForm>
</template>
<script lang="ts" name="Login" setup>
import { useUserStoreWithOut } from '@/store/modules/user'
import { getUserProfile } from '@/api/system/user/profile'
import { useDictStoreWithOut } from '@/store/modules/dict'
import EnterpriseForm from './enterpriseForm.vue'
import AuthorizeForm from './authorizeForm.vue'
import RegisterForm from './registerForm.vue'
import ForgotForm from './forgotForm.vue'
import * as authUtil from '@/utils/auth'
import * as LoginApi from '@/api/login'
import { useRouter } from 'vue-router'
import { cloneDeep } from 'lodash'

const userStore = useUserStoreWithOut()
const state = ref(0)
const length = ref('0')
const redirect = ref('')
const slideVerifyRef = ref()
const forgotFormRef = ref()
const registerFormRef = ref()
const enterpriseFormRef = ref()
const authorizeFormRef = ref()
const isShowIcon = ref(false)
const isVerifySuccess = ref(true)
const validMess = ref('获取验证码')
const { push } = useRouter()
const isRegister = ref(true)
const message = useMessage()
const switchImg = ref()
let countNum = ref(59)
let intervalId = null
const userId = ref()
// const sign = ref()
const loginForm = ref({
  username: undefined,
  password: undefined,
  mobile: undefined,
  code: undefined,
  loginType: 1,
  reqSystemSource: 2
})

const isRegisterIcon = computed(() => {
  if (isRegister.value) {
    return new URL(
      '@/assets/imgs/error-icon.png',
      import.meta.url
    ).href
  }
  return new URL(
    '@/assets/imgs/yes-icon.png',
    import.meta.url
  ).href
})

const loginWayIcon = computed(() => {
  if (loginForm.value.loginType === 2) {
    return new URL(
      '@/assets/imgs/accunt-icon.png',
      import.meta.url
    ).href
  }
  if (loginForm.value.loginType === 1) {
    return new URL(
      '@/assets/imgs/phone-icon.png',
      import.meta.url
    ).href
  }
})

const loginWayText = computed(() => {
  if (loginForm.value.loginType === 2) {
    return '账号密码登录'
  }
  if (loginForm.value.loginType === 1) {
    return '手机验证码登录'
  }
})

const toggleWay = () => {
  if (loginForm.value.loginType === 1) {
    loginForm.value.loginType = 2
  } else {
    loginForm.value.loginType = 1
  }
  switchMouseover()
  isVerifySuccess.value = true
}

const switchMouseover = () => {
  if (loginForm.value.loginType === 2) {
    switchImg.value = new URL(
      '@/assets/imgs/accunt-active-icon.png',
      import.meta.url
    ).href
  }
  if (loginForm.value.loginType === 1) {
    switchImg.value = new URL(
      '@/assets/imgs/phone-active-icon.png',
      import.meta.url
    ).href
  }
}

const switchMouseleave = () => {
  if (loginForm.value.loginType === 2) {
    switchImg.value = new URL(
      '@/assets/imgs/accunt-icon.png',
      import.meta.url
    ).href
  }
  if (loginForm.value.loginType === 1) {
    switchImg.value = new URL(
      '@/assets/imgs/phone-icon.png',
      import.meta.url
    ).href
  }
}

const validPhone = async () => {
  if (!loginForm.value.mobile) {
    isShowIcon.value = false
    isRegister.value = true
    return
  }
  if (!/^1[3-9]\d{9}$/.test(loginForm.value.mobile)) {
    isRegister.value = true
    message.warning('请输入正确的手机号')
    return
  }
  if (userId.value) {
    isShowIcon.value = false
    return
  }
  isShowIcon.value = true
  const res = await LoginApi.validLogin({
    mobile: loginForm.value.mobile,
    loginType: loginForm.value.loginType
  })
  if (res.code === 0) {
    isRegister.value = false
  } else {
    isRegister.value = true
    ElNotification.warning(res.msg)
  }
}

const countNumFun = () => {
  if (countNum.value <= 0) {
    clearInterval(intervalId)
    countNum.value = 59
    validMess.value = '获取验证码'
    return
  }
  countNum.value -= 1
  validMess.value = countNum.value + 's'
}

const onVerifySuccess = (value) => {
  isVerifySuccess.value = value
}

const getVerifyCode = async () => {
  if (!loginForm.value.mobile) {
    message.warning('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(loginForm.value.mobile)) {
    message.warning('请输入正确的手机号')
    return
  }
  if (isVerifySuccess.value) {
    message.warning('请按住滑块，拖到最右边')
    return
  }
  if (isRegister.value && !userId.value) {
    return
  }
  const res = await LoginApi.sendSmsCode({
    mobile: loginForm.value.mobile,
    scene: 19
  })
  message.success('验证码发送成功')
  isVerifySuccess.value = true
  slideVerifyRef.value?.initSlider()
  validMess.value = countNum.value + 's'
  intervalId = setInterval(() => {
    countNumFun()
  }, 1000)
}

const openRegisterForm = () => {
  registerFormRef.value?.open()
}

const openForgotForm = () => {
  forgotFormRef.value?.open(loginForm.value.username)
}

const handleLogin = async () => {
  if (loginForm.value.loginType === 1) {
    if (!loginForm.value.username) {
      message.warning('请输入账号')
      return
    }
    if (!loginForm.value.password) {
      message.warning('请输入密码')
      return
    }
  }
  if (loginForm.value.loginType === 2) {
    if (!loginForm.value.mobile) {
      message.warning('请输入手机号')
      return
    }
    if (!loginForm.value.code) {
      message.warning('请输入验证码')
      return
    }
  }
  const data = cloneDeep(loginForm.value)
  if (loginForm.value.loginType === 1) {
    delete data.mobile
    delete data.code
  }
  if (loginForm.value.loginType === 2) {
    delete data.username
    delete data.password
  }
  if (userId.value) {
    data['reqSystemSource'] = 1
  }
  const res = await LoginApi.login(data)
  if (res.code === 0) {
    const result = res.data || {}
    storeLoginInfo(result)
    authUtil.setLoginForm({
      account:
        loginForm.value.loginType === 1
          ? loginForm.value.username
          : loginForm.value.mobile,
      loginType: loginForm.value.loginType
    })
    userStore.getTenantList()
    handleAuthorize()
  } else if (res.code === 1002000012) {
    authUtil.setLoginForm({
      account:
        loginForm.value.loginType === 1
          ? loginForm.value.username
          : loginForm.value.mobile,
      loginType: loginForm.value.loginType
    })
    enterpriseFormRef.value.open(loginForm.value.mobile)
  } else {
    ElNotification.warning(res.msg)
  }
}

const storeLoginInfo = (result) => {
  authUtil.setToken(result)
  authUtil.setUserId(result.userId)
  authUtil.setTenantId(result.tenantId)
}

const handleAuthorize = async () => {
  if (userId.value) {
    const suc = await LoginApi.haveAuthorize({
      userAccountId: userId.value
    })
    if (suc === 1) {
      authorizeFormRef.value.open({
        userAccountId: userId.value
      })
      return
    }
  }
  loginPage('/')
}

const enterpriseCallback = async () => {
  userStore.getTenantList()
  handleAuthorize()
}

const authorizeCallback = (flag) => {
  userStore.getTenantList()
  loginPage('/')
}

const loginPage = (path) => {
  ElLoading.service({
    lock: true,
    text: '正在加载系统中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  push({ path })
  setTimeout(() => {
    const loadingInstance = ElLoading.service()
    loadingInstance.close()
  }, 400)
}

const getUrlParams = (url) => {
  const params = {}
  const query = url.split('?')[1]
  if (query) {
    const queryParts = query.split('&')
    queryParts.forEach((part) => {
      const [key, value] = part.split('=')
      params[key] = decodeURIComponent(value)
    })
  }
  return params
}

onMounted(() => {
  authUtil.clearCacheAll()
  const params = getUrlParams(location.href)
  userId.value = params?.userId
  if (userId.value) {
    loginForm.value.loginType = 2
  }
  switchMouseleave()
})
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  font-family: PingFang SC, PingFang SC-500;
  background-image: url('@/assets/imgs/login-bg.png');

  .logo {
    position: absolute;
    top: 53px;
    left: 112px;
    height: 100px;
    width: auto;
  }

  .login-box {
    position: absolute;
    right: 180px;
    height: 100%;
    display: flex;
    align-items: center;

    .login-panel {
      width: 440px;
      padding: 8px;
      background-color: rgba(255, 255, 255, 0.5);
    }
  }
}

.login-card {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 32px 32px 16px 32px;
  background-color: #ffffff;

  .title {
    font-size: 28px;
    font-weight: 500;
    margin-bottom: 30px;

    span {
      color: #409efe;
    }
  }

  .form-item {
    font-family: system-ui !important;
  }

  .form-item .el-button {
    font-size: 16px;
  }

  .count-btn.el-button {
    color: #409efe !important;
  }

  .form-item + .form-item {
    margin-top: 16px;
  }

  .verify-btn {
    color: #409efe;
    cursor: pointer;
  }

  > img {
    position: absolute;
    top: 0;
    right: 0;
  }

  .justify-between {
    margin-bottom: 10px;
  }

  .other-way {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #535559;
    padding: 24px 0 16px 0;

    span.label {
      position: relative;
      margin-bottom: 16px;
    }

    span.label::before {
      content: '';
      display: inline-block;
      position: absolute;
      width: 40px;
      height: 1px;
      top: 10px;
      right: 90px;
      background: #535559;
    }

    span.label::after {
      content: '';
      display: inline-block;
      position: absolute;
      width: 40px;
      height: 1px;
      top: 10px;
      left: 90px;
      background: #535559;
    }

    .text-center {
      color: #909399;
    }
  }

  :deep(.el-input--default) {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
  }

  :deep(.el-button--large) {
    font-size: 16px;
  }

  :deep(.el-input__password) {
    font-size: 18px;
  }
}

a {
  position: absolute;
  color: #409efe;
  font-size: 16px;
  bottom: 20px;
  left: 50%;
  transform: translateX(-92px);
}
</style>
